import React, {Component} from 'react';
import { Form, Input, Button, Icon, Modal, message } from 'antd';
import { Link, history } from 'react-router-dom';
import './index.less';
import axios from 'axios';
import {connect} from 'react-redux';
import Bread from '../common/Bread/index';
const FormItem = Form.Item;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

class changephone extends Component {
    constructor(props) {
      super(props);
      this.state = {
        visible: false,
        autoCompleteResult: [],
        getCode: '',
        newMobile: '',
        oldMobile: '',
      }
    }
    showModal = () => {
        this.setState({
            visible: true,
        });
      }
    handleOk = () => {
        this.setState({visible: false });
    }
    handleCancel = () => {
        this.setState({ visible: false });
    }
    handleSubmit = (e) => {
      e.preventDefault();
      const _this = this;
      const Token = localStorage.getItem("token");
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
              axios({
                method: 'post',
                url: '/api/customer/user/resetTel',
                data: values,
                headers: {
                  'Content-Type': 'application/json',
                  Authorization:Token,
                },
              })
              .then(function(response){
                  if(response.data.status == 'false'){
                    message.warning(response.data.message);
                  }else if(response.data.message == '恭喜您已经成功修改手机号！') {
                    _this.props.form.resetFields();
                    _this.setState({
                      visible: true
                    })
                  }
              })
            }else {
                console.log('Received values of form: ', values);
            }
          // this.SubmitPost(values)
      });
    }

    getMobile=(e)=>{
      this.setState({
        newMobile: e.target.value
      })
    }

    handleCode =()=>{
      const _this = this;
      let sec = 60;
      const clickTime = new Date().getTime();
      const newMobile = this.state.newMobile;
      const Token = localStorage.getItem("token");
      localStorage.setItem("changePhoneclickTime",clickTime);
      if(this.state.oldMobile == this.state.newMobile){
          message.warning('两次输入的手机号不能一致')
          return false;
      }else if(this.state.getCode !== '获取验证码'){
          return false;
      }else{
          axios({
            method: 'get',
            url: '/api/customer/user/approval/sendMsg?mobile='+ newMobile,
            headers: {
              'Content-Type': 'application/json',
              Authorization:Token,
            }
          })
          .then(function(response){
            if(response.data.code == '201'){
              message.warning('请输入正确的手机号');
            }else if(response.data.code == '202'){
              message.warning('获取手机验证码失败');
            }else if(response.data.code == '200') {
              const timer = setInterval(function(){
                sec--;
                if(sec < 0){
                  clearInterval(timer);
                  _this.setState({
                    getCode:  '获取验证码',
                  })
                  localStorage.setItem("changePhoneclickTime","");
                }else {
                  _this.setState({
                    getCode:  sec + 's 后重新获取',
                  })
                }
              },1000)
            }
          })
        }
  }

  componentWillMount(){
    const _this = this;
    const nowDate = new Date().getTime();
    let sec = localStorage.getItem("changePhoneclickTime");
    const currentTime = (nowDate - sec)/1000;
    let delta = Math.round(60 - currentTime);
    const timer = setInterval(function(){
      delta--;
      if(delta < 0){
        clearInterval(timer);
        _this.setState({
          getCode:  '获取验证码',
        })
      }else {
        _this.setState({
          getCode:  delta + 's 后重新获取',
        })
      }
    },1000)

    const Token = localStorage.getItem("token");
    axios({
      method: 'get',
      url: '/api/customer/user/getTel',
      headers: {
        'Content-Type': 'application/json',
        Authorization:Token,
      }
    })
    .then(function(response){
      if(response.data.code == '200'){
        _this.setState({
            oldMobile: response.data.data,
        })
      }
    })
    .catch(function(error){
      message.error('获取手机号失败') 
    })
  }

  onFocusFn=(e)=>{
    if(e.target.value == ''){
      e.target.type='text'
    }else{
       // console.log(e.target.value)
      e.target.type='password'
    }
  }

    render() {
      const { getFieldDecorator } = this.props.form;
      const { autoCompleteResult, visible } = this.state;
      const disabled = this.state.getCode !== '获取验证码' ? "disabled" : "";
      return (
          <div>
            <Bread bread={['账户服务',['手机修改','changePhone']]}/>
            <div className="changeBox">           
            <Form onSubmit={this.handleSubmit}>
              <div>
                  <h3 className="changeTitle">手机修改</h3>                  
                    <FormItem
                        label="账户密码"
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 11 }}
                    >
                      {getFieldDecorator('password', {
                        rules: [{ required: true, message: '请输入账户密码' }],
                      })(
                        <Input type="text" placeholder="请输入账户密码" onChange = {this.onFocusFn} />
                      )}
                  </FormItem>
                  <FormItem
                      label="原手机号"
                      labelCol={{ span: 5 }}
                      wrapperCol={{ span: 11 }}
                  > 
                      <Input disabled value={this.state.oldMobile} />
                  </FormItem>
                  <FormItem className="namePhone"
                      label="新手机号"
                      labelCol={{ span: 5 }}
                      wrapperCol={{ span: 11 }}
                  >
                      {getFieldDecorator('telPhone', {
                          rules: [{required: true, message: '请输入新手机号'}],
                      })(
                          <Input className="phoneText" placeholder="请输入新手机号" maxLength={11} onChange = {this.getMobile} />   
                      )}
                      <Button
                          className="yzmBtn"
                          type= "primary"
                          size="small"
                          // disabled
                          disabled={disabled}
                          onClick = {this.handleCode}
                        >
                        {this.state.getCode}
                      </Button>
                  </FormItem>
                  <FormItem
                      label="短信验证码"
                      labelCol={{ span: 5 }}
                      wrapperCol={{ span: 11 }}
                  > 
                    {getFieldDecorator('attr1',{
                      rules: [{required: true, message: '请输入短信验证码，仅限数字', pattern: /^[0-9]+$/}]
                    })(
                      <Input type="text" placeholder="请输入短信验证码，仅限数字" maxLength={8} />
                    )}
                  </FormItem>
                  <div className="confirmChange">
                    <Button type="primary" htmlType="submit">确认修改</Button>
                  </div>
                </div>
            </Form>
            <Modal
              visible={visible}
              title="提示"
              onOk={this.handleOk}
              onCancel={this.handleCancel}
              footer={[
                <Button key="submit" type="primary" onClick={this.handleOk}>
                  确认
                </Button>,
              ]}
            >
              <p className="title">恭喜您已经成功修改手机号！</p>
            </Modal>
          </div>
          </div>
      )
    }
  }
  
const changePhone = Form.create()(changephone);
export default connect((state) => {
  return { ...state };
})(changePhone);


